<?php
function sessionChekIn($sessId, $userId = 0)
{
	
	if($userId == '')
	{ $userId = 0; }
	
	$select = 'UPDATE '.DB_PERFIX.'sessions SET session_time = NOW() WHERE session_id="'.$sessId.'" AND session_user_id='.$userId.' LIMIT 1;';
	$result = mysql_query($select);
	
	if(mysql_affected_rows() < 1)
	{
		$user_ip = $_SERVER['REMOTE_ADDR'];
		if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_CLIENT_IP']; }
		if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
		
		$insert = 	' INSERT INTO `'.DB_PERFIX.'sessions` (`session_id` , `session_user_id` , `session_start` , `session_time` , `session_ip` , `session_page` , `session_logged_in` , `session_gid` )';
		$insert .= 	' VALUES (\''.session_id().'\', \''.$userId.'\', NOW( ), NOW( ), \''.$user_ip.'\', \''.$_GET['com_id'].'\', \'0\', \'0\');';
		$result = mysql_query($insert);
	}
	
	if($userId > 0)
	{
		$updateUser = ' UPDATE `'.DB_PERFIX.'users` SET lastvisitDate = NOW() WHERE id='.$userId.';';
		$result = mysql_query($updateUser);
	}
}

function sessionChekOut()
{
	/*
	$time = mktime(date("H"), date("i")-(USER_TIMEOUT/2), date("s"), date("m"), date("d"),  date("Y"));
	$time_chek = (date("Y-m-d H:i:s ",$time));
	
	$select = 'SELECT session_user_id, (session_time-session_start) AS online_time FROM '.DB_PERFIX.'sessions WHERE session_user_id > 0 AND session_time < "'.$time_chek.'";';
	$result = mysql_query($select);
	
	while($row = mysql_fetch_array($result))
	{ 
		$user['id'] = $row['session_user_id']; 
		$user['online_time'] = $row['online_time'];
		
		$time = mktime(0, 0, $user['online_time'], 0, 0, 0);
		$time = (date("H:i:s ",$time)); 
		
		$updateUser = 'UPDATE '.DB_PERFIX.'user_details SET online_time = ADDTIME(online_time , "'.$time.'") WHERE id='.$user['id'].';';
		$result2 = mysql_query($updateUser);
	}
	
	$delete = 'DELETE FROM '.DB_PERFIX.'sessions WHERE session_time < "'.$time_chek.'";';
	$result = mysql_query($delete);
	*/
}

function loginUser($username, $password, $remember)
{
	$error[0] = 'No such username';
	$username = trim($username);
	$password = trim($password);
	$password = stripslashes($password);
	$password = md5($password);
	
	$select = 'SELECT * FROM '.DB_PERFIX.'users WHERE username LIKE ("'.$username.'");';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['id'] = $row['id'];
			$user['username'] = $row['username'];
			$user['password'] = $row['password'];
			$user['level'] = $row['level'];
		}
		$error[0] = "";
		$error[1] = 'Wrong password';
	}
	if(($user['username'] == $username) && ($password == $user['password']))
	{
		$_SESSION['logged'] = 1;
		$_SESSION['userid'] = $user['id'];
		$_SESSION['username'] = $user['username'];
		if($remember)
		{ $_SESSION['remember'] = 'true'; }
			
		$user_ip = $_SERVER['REMOTE_ADDR'];
		if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_CLIENT_IP']; }
		if (trim($user_ip) == '') { $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }
		
		$delete = 'DELETE FROM '.DB_PERFIX.'sessions WHERE session_user_id='.$user['id'].' OR session_id = "'.session_id().'" LIMIT 1;';
		$result = mysql_query($delete);
		$insert = 	' INSERT INTO `'.DB_PERFIX.'sessions` (`session_id` , `session_user_id` , `session_start` , `session_time` , `session_ip` , `session_page` , `session_logged_in` , `session_gid` )';
		$insert .= 	' VALUES (\''.session_id().'\', \''.$user['id'].'\', NOW( ), NOW( ), \''.$user_ip.'\', \''.$_GET['com_id'].'\', \'1\', \''.$user['level'].'\');';
		$result = mysql_query($insert);
		$update = 	' UPDATE `'.DB_PERFIX.'users` SET lastvisitDate = NOW() WHERE id='.$user['id'].';';
		$result = mysql_query($update);
		if($result > 0)
		{
			$error[0] = "";
			$error[1] = "";
			$user['userid'] = $_SESSION['userid'];
			$user['username'] = $_SESSION['username'];
		}
		return $error;
	}
	else
	{ return $error; }
}

function logoutUser($userid, $username)
{
	$username = trim($username);
	if($userid != '')
	{
		$whereString = ' id='.$userid;
	}
	if(!$whereString && ($username != ''))
	{
		$whereString = ' username LIKE ("'.$username.'")';
	}
	if($whereString != '')
	{
		$select = 'SELECT id FROM '.DB_PERFIX.'users WHERE '.$whereString.';';
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{ $user['id'] = $row['id']; }
			
			$updateUser = ' UPDATE `'.DB_PERFIX.'users` SET lastvisitDate = NOW() WHERE id='.$user['id'].';';
			$result = mysql_query($updateUser);
			
			$selectTime = 'SELECT (session_time-session_start) AS online_time FROM '.DB_PERFIX.'sessions WHERE session_user_id='.$user['id'].' LIMIT 1;';
			$result = mysql_query($selectTime);
			while($row = mysql_fetch_array($result))
			{
				$user['online_time'] = $row['online_time'];
			}
			$time = mktime(0, 0, $user['online_time'], 0, 0, 0);
			$time = (date("H:i:s ",$time)); 
			
			$updateUser = ' UPDATE `'.DB_PERFIX.'user_details` SET online_time = ADDTIME(online_time , "'.$time.'") WHERE id='.$user['id'].';';
			$result = mysql_query($updateUser);
		
			$delete = 'DELETE FROM '.DB_PERFIX.'sessions WHERE session_user_id='.$user['id'].';';
			$result = mysql_query($delete);
			
			unset($_SESSION['logged']);
			unset($_SESSION['userid']);
			unset($_SESSION['username']);
			unset($_COOKIE[session_name()]);
			
			return $result;
		}
	}
}

function getUserId($username='', $email='')
{
	$usrid = 0;
	$whereString = 'WHERE id > 0 ';
	if($username != '')
	{
		$username 	  = strip_tags(trim($username));
		$whereString .= ' AND username="'.$username.'" ';
	}
	if($email != '')
	{
		$country 	  = strip_tags(trim($email));
		if($username != '')
		{ $whereString .= ' OR email="'.$email.'" '; }
		else
		{ $whereString .= ' AND email="'.$email.'" '; }
	}

	$select = 'SELECT id FROM '.DB_PERFIX.'users '.$whereString.';';
	
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{ $usrid = $row['id']; }
	}
	return $usrid;
}


function addNewUser($username, $password, $email, $txt)
{
	$time=time();
	$time_insert = (date("Y-m-d H:i:s ",$time)); 
	$activation = md5($time);
	$level = 1;
	$password = trim($password);
	$password = stripslashes($password);
	$usrid = 0;
	$usrid = getUserId($username, $email);
	if($usrid == 0)
	{
		$insert  = 'INSERT INTO '.DB_PERFIX.'users (`id`, `username`, `email`, `password`, `registerDate`, `lastvisitDate`, `activation`)'; 
		$insert .= "VALUES (NULL, '".$username."', '".$email."', '".md5($password)."', '".$time_insert."', NOW(), '".$activation."');";
		$result = mysql_query($insert);
		if($result > 0)
		{
			//hello
			//thank_registering_at
			//activation_link_info
			//activation_link_info_after 
			//activation_link_info_after2
			$body  = ucfirst($txt->getWord('hello')).' '.$username.'<br />';
			$body .= ucfirst($txt->getWord('thank_registering_at')).' '.$site['title'].'<br />';
			$body .= ucfirst($txt->getWord('activation_link_info')).'<br />';
			$body .= '<a href="'.SITE_URL.'?c=16&amp;active='.$activation.'">'.SITE_URL.'?c=16&amp;active='.$activation.'</a><br />';
			$body .= ucfirst($txt->getWord('activation_link_info_after')).' '.SITE_URL.' '.$txt->getWord('activation_link_info_after2').'<br /><br />';
			$body .= ucfirst($txt->getWord('username')).':'.$username.'<br />';
			$body .= ucfirst($txt->getWord('password')).':'.$password.'<br />';
			if($body != '')
			{
				mail($email, 'Welcome to '.SITE_URL, $body, "From: post@".DOMAIN."\r\nX-Mailer: PHP/" . phpversion() . "\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n");
			}
			return $result;
		}
	}
}

function deleteMember($userid)
{
	//Delete all videos user has posted
	deleteMemberVideos($userid);
	deleteMemberGalleries($userid);
	deleteMemberOglase($userid);
	
	$delete = 'DELETE FROM '.DB_PERFIX.'user_votes WHERE user_id='.$userid.' OR voter_id='.$userid.';';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'user_friends WHERE user_id='.$userid.' OR friend_id='.$userid.';';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'user_comments WHERE from_id='.$userid.' OR to_id='.$userid.';';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'user_pm WHERE from_id='.$userid.' OR to_id='.$userid.';';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'user_profile WHERE id='.$userid.';';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'user_details WHERE id='.$userid.';';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'users WHERE id='.$userid.';';
	$result = mysql_query($delete);
	
}

function sendNewPassword($email)
{
	$select = 'SELECT id, username FROM '.DB_PERFIX.'users WHERE email="'.$email.'" LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$userid = $row['id'];
			$username = $row['username'];
		}
	}
	if($userid > 0)
	{
		$possible = '0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPRSTUVZXQW';
		$code = '';
		$i = 0;
		while ($i < 7) 
		{ 
			$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
			$i++;
		}
		$password = md5($code);
		
		$update = 'UPDATE '.DB_PERFIX.'users SET password="'.$password.'" WHERE id='.$userid.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{
			mail($email, $site['title'].' new password', 'Hello '.$username.'!  Your new password is:'.$code.'', 'From: webmaster@'.DOMAIN);
			return 'You have been sent a new password now to '.$email.'.';
		}
	}
	else
	{
		return 'No user found with this e-mail: '.$email.'.';
	}
}

function getUser($userid)
{
	$select = 'SELECT * FROM '.DB_PERFIX.'users WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['id'] = $row['id'];
			$user['username'] = $row['username'];
			$user['email'] = $row['email'];
			$user['password'] = $row['password'];
			$user['level'] = $row['level'];
			$user['image'] = $row['image'];
		}
		return $user;
	}
}

function getUserDetails($userid)
{
	$select = 'SELECT * FROM '.DB_PERFIX.'user_details WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['gender'] = $row['gender'];
			$user['country'] = $row['country'];
			$user['city'] = $row['city'];
			$user['zip'] = $row['zip'];
			$user['address'] = $row['address'];
			$user['bdate'] = $row['bdate'];
			$user['bday'] = substr($user['bdate'],8,2);
			$user['bmonth'] = substr($user['bdate'],5,2);
			$user['byear'] = substr($user['bdate'],0,4);
			$user['age'] = getUserAge($user['bday'], $user['bmonth'], $user['byear']);
		}
		return $user;
	}
	else
	{
		$user['gender'] = 0;
		$user['country'] = '';
		$user['city'] = '';
		$user['zip'] = '';
		$user['address'] = '';
		$user['bdate'] = '';
		$user['age'] = 0;
		chekUserDetails($id);
		return $user;
	}
}

function getUserAll($userid)
{
	$select = 'SELECT id, username, email, level, image FROM '.DB_PERFIX.'users WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['id'] = $row['id'];
			$user['username'] = $row['username'];
			$user['email'] = $row['email'];
			$user['level'] = $row['level'];
			$user['image'] = $row['image'];
		}
	}
	$select = 'SELECT * FROM '.DB_PERFIX.'user_details WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['gender'] = $row['gender'];
			if($user['gender'] == '1')
			{ $user['gendertxt'] = 'Male'; }
			else
			{ $user['gendertxt'] = 'Female'; }
			$user['country'] = $row['country'];
			$user['state'] = $row['state'];
			$user['city'] = $row['city'];
			$user['zip'] = $row['zip'];
			$user['address'] = $row['address'];
			$user['bdate'] = $row['bdate'];
			$user['bday'] = substr($user['bdate'],8,2);
			$user['bmonth'] = substr($user['bdate'],5,2);
			$user['byear'] = substr($user['bdate'],0,4);
			$user['age'] = getUserAge($user['bday'], $user['bmonth'], $user['byear']);
		}
	}
	else
	{
		createUserDetails($user['id']);
	}
			
	$select = 'SELECT * FROM '.DB_PERFIX.'user_rating WHERE user_id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if($result[0]['user_id'] > 0)
	{
		$user['stars'] = $result[0]['stars'];
		$user['votes'] = $result[0]['votes'];
		$user['avg'] = round(($user['stars']/$user['votes']));
	}
	else
	{
		createUserRating($user['id']);
		$user['stars'] = 0;
		$user['votes'] = 0;
		$user['avg'] = 0;
	}
	return $user;
}
function getUserAllProfile($userid)
{
	$select = 'SELECT id, username, email, level, image FROM '.DB_PERFIX.'users WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['id'] = $row['id'];
			$user['username'] = $row['username'];
			$user['email'] = $row['email'];
			//$user['password'] = $row['password'];
			$user['level'] = $row['level'];
			$user['image'] = $row['image'];
		}
	}
	$select = 'SELECT * FROM '.DB_PERFIX.'user_details WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['gender'] = $row['gender'];
			if($user['gender'] == '1')
			{ $user['gendertxt'] = 'Male'; }
			else
			{ $user['gendertxt'] = 'Female'; }
			
			$user['country'] = $row['country'];
			$user['state'] = $row['state'];
			$user['city'] = $row['city'];
			$user['zip'] = $row['zip'];
			$user['address'] = $row['address'];
			$user['bdate'] = $row['bdate'];
			$user['bday'] = substr($user['bdate'],8,2);
			$user['bmonth'] = substr($user['bdate'],5,2);
			$user['byear'] = substr($user['bdate'],0,4);
			$user['age'] = getUserAge($user['bday'], $user['bmonth'], $user['byear']);
		}
	}
	else
	{
		createUserDetails($user['id']);
	}
	
	$select = 'SELECT bg, bg_style, site_template, about, views, sports, stats, teams, teams_diss, logo FROM '.DB_PERFIX.'user_profile WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$user['bg'] = $row['bg'];
			$user['bg_style'] = $row['bg_style'];
			$user['site_template'] = $row['site_template'];
			$user['about'] = $row['about'];
			$user['views'] = $row['views'];
			$user['sports'] = $row['sports'];
			$user['stats'] = $row['stats'];
			$user['teams'] = $row['teams'];
			$user['teams_diss'] = $row['teams_diss'];
			$user['logo'] = $row['logo'];
		}
	}
	else
	{
		createUserProfile($user['id']);
		$user['bg'] = '';
		$user['bg_style'] = '';
		$user['site_template'] = '';
		$user['about'] = '';
		$user['views'] = 0;
		$user['sports'] = '';
		$user['stats'] = '';
		$user['teams'] = '';
		$user['teams_diss'] = '';
		$user['logo'] = '';
	}
	
	
	$select = 'SELECT * FROM '.DB_PERFIX.'user_rating WHERE user_id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if($result[0]['user_id'] > 0)
	{
		$user['stars'] = $result[0]['stars'];
		$user['votes'] = $result[0]['votes'];
		$user['avg'] = round(($user['stars']/$user['votes']));
	}
	else
	{
		createUserRating($user['id']);
		$user['stars'] = 0;
		$user['votes'] = 0;
		$user['avg'] = 0;
	}
	
	return $user;
}
function getUserBg($userid)
{
	$item = '';
	if($userid > 0)
	{
		$select = 'SELECT bg, bg_style FROM '.DB_PERFIX.'user_profile WHERE id='.$userid.' LIMIT 1;';
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				$item['bg'] = $row['bg'];
				$item['bg_style'] = $row['bg_style'];
			}
		}
	}
	return $item;
}
function createUserRating($id)
{
	$insert  = 'INSERT INTO '.DB_PERFIX.'user_rating (`user_id` , `stars` , `votes`)'; 
	$insert .= 'VALUES ('.$id.' , 0 , 0);';
	$result = mysql_query($insert);
	return $result;
}
function getUserAge($bday=0, $bmonth=0, $byear=0)
{
	$age = mktime(0, 0, 0, date("m")-$bmonth, date("d")-$bday,  date("Y")-$byear);
	$age = date("y",$age);
	if($byear < 1910)
	{ $age = ""; }
	return $age;
}

function uploadProfileImage($userid, $old_image)
{
	if (image_valid($_FILES['profile_image']['type']) && ($_FILES['profile_image']['name'] != ""))
	{
		if($_FILES["profile_image"]["size"] < 20000)
		{
			$error['profile_image'] = "image size too big:".$_FILES["profile_image"]["size"];
		}
		$type = $_FILES['profile_image']['type'];
		$temp_name = $_FILES["profile_image"]["name"];
		$extension = substr($temp_name,-3);
		$new_name = $userid.md5(uniqid()).".".$extension;
		
		if (is_file(USER_IMAGE_PATH.$old_image))
		{
			if (!unlink(USER_IMAGE_PATH.$old_image))
			{$error['profile_image'] = "Error deleting old profile image ";}
			else
			{$error['profile_image'] = 'Deleted old image';}
		}
		
		move_uploaded_file($_FILES["profile_image"]["tmp_name"], USER_IMAGE_PATH.$new_name);
		$ImageStatus = "Stored in: " .USER_IMAGE_PATH.$new_name;
		resizePhoto(USER_IMAGE_PATH.$new_name, $type, MAX_IMAGE_W, MAX_IMAGE_H);
		$i=0;
		foreach($thumb['USER_IMAGE'] as $thumb)
		{
			if (is_file(USER_IMAGE_THUMB_PATH.$thumb['MAXW'].'_'.$old_image))
			{
				if (!unlink(USER_IMAGE_THUMB_PATH.$thumb['MAXW'].'_'.$old_image))
				{$error['profile_image'] = "Error deleting old profile image thumbnail";}
				else
				{$error['profile_image'] = 'Deleted old image thumbnail';}
			}
			if (is_file(USER_IMAGE_THUMB_PATH.$old_image))
			{
				if (!unlink(USER_IMAGE_THUMB_PATH.$old_image))
				{$error['profile_image'] = "Error deleting old profile image thumbnail";}
				else
				{$error['profile_image'] = 'Deleted old image thumbnail';}
			}
			$i++;
		}
		$daName = $new_name;
		$i=0;
		foreach($thumb['USER_IMAGE'] as $thumb)
		{
			if($i>1)
			{ $new_name = $daName; }
			else
			{ $new_name = $thumb['MAXW'].'_'.$daName; }
			$i++;
			
			if (is_file(USER_IMAGE_PATH.$daName))
			{
				if (copy(USER_IMAGE_PATH.$daName, USER_IMAGE_THUMB_PATH.$new_name)) 
				{
					if($thumb['RESIZING_TYPE'] == 0)
					{ resizePhoto(USER_IMAGE_THUMB_PATH.$new_name, $type, $thumb['MAXW'], $thumb['MAXH']); }
					else
					{ makeIcons_MergeCenter(USER_IMAGE_THUMB_PATH.$new_name, USER_IMAGE_THUMB_PATH.$new_name, $thumb['MAXW'], $thumb['MAXH']); }
					
					$insert  = 'UPDATE '.DB_PERFIX.'users SET image="'.$daName.'" WHERE id='.$userid.' LIMIT 1 ;'; 
					$result = mysql_query($insert);
					if ($result > 0)
					{ $error['profile_image'] = "<strong>Image Uploaded </strong>"; }
				}
			}
		}
		return $error['profile_image'];
	}
}

function updateUsername($id, $username)
{
	$username = trim($username);
	$select = 'SELECT username FROM '.DB_PERFIX.'users WHERE username LIKE ("'.$username.'");';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$error['username'] = 'Username allready exists';
	}
	else
	{
		$error['username'] = "Changing ";
		$update = 'UPDATE '.DB_PERFIX.'users SET username="'.$username.'", lastvisitDate=NOW( ) WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{
			$error['username'] = "Username Changed";
		}
		else
		{
			$error['username'] = "Username Not Changed";
		}
		
	}
	return $error['username'];
}

function updateEmail($id, $email)
{
	$email = trim($email);
	$select = 'SELECT email FROM '.DB_PERFIX.'users WHERE email ="'.$email.'";';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$error['email'] = 'Email allready exists';
		return $error['email'];
	}
	else
	{
		$error['email'] = "Changing email";
		$update = 'UPDATE '.DB_PERFIX.'users SET email="'.$email.'", lastvisitDate=NOW( ) WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{
			$error['email'] = "Email Changed";
		}
		else
		{
			$error['email'] = "Email Not Changed";
		}
		
	}
	return $error['email'];
}
function updatePassword($id, $password, $newpassword)
{
	$newpassword = trim($newpassword);
	$newpassword = stripslashes($newpassword);
	
	$select = 'SELECT username, password, email FROM '.DB_PERFIX.'users WHERE id='.$id.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$curpass = $row['password'];
			$username = $row['username'];
			$email	= $row['email'];
		}
	}
		
	if($curpass != md5($password))
	{ $error['password'] = "Invalid Password"; }
	else
	{
		$update = 	' UPDATE `'.DB_PERFIX.'users` SET password = "'.md5($newpassword).'" WHERE id='.$id.';';
		$result = mysql_query($update);
		if($result > 0)
		{
			$error['password'] = "Password Changed";
			mail($email, $site['title'].' new password', 'Hello '.$username.'!  Your new password is:'.$newpassword.'', 'From: webmaster@'.DOMAIN);
		}
	}
	return $error['password'];
}
function updateUserDetails($id, $gender='NULL', $country='NULL', $state='NULL', $city='NULL', $zip='NULL', $address='NULL', $bday='NULL', $bmonth='NULL', $byear='NULL')
{
	if($bday > cal_days_in_month(CAL_GREGORIAN,$bmonth,$byear))
	{ $bday = cal_days_in_month(CAL_GREGORIAN,$bmonth,$byear); }
	
	if(getUserDetails($id))
	{
		$setString = 'gender='.$gender.', ';
		$setString = $setString.'bdate="'.$byear.'-'.$bmonth.'-'.$bday.'" , ';
		$setString = $setString.'country="'.$country.'" , ';
		$setString = $setString.'state='.$state.', ';
		$setString = $setString.'city="'.$city.'" , ';
		$setString = $setString.'zip='.$zip.', ';
		$setString = $setString.'address="'.$address.'" ';
		
		$update = 'UPDATE '.DB_PERFIX.'user_details SET '.$setString.' WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		
		if($result > 0)
		{
			$error['update'] = 'Profile Updated<br />';
			return $error['update'];
		}
		else
		{ 
			$error['update'] = 'Error updating profile<br />'.$update;
			return $error['update'];
		}
	}
}
function chekUserDetails($id)
{	
	$select  = 'SELECT id FROM '.DB_PERFIX.'user_details WHERE id='.id.';'; 
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{ 
		echo 'found';
		return true; 
	}
	else
	{ createUserDetails($id); }
	
}
function createUserDetails($id)
{
	$insert  = 'INSERT INTO '.DB_PERFIX.'user_details (`id` , `bdate`, `country`)'; 
	$insert .= 'VALUES ('.$id.' , NULL , NULL);';
	
	$result = mysql_query($insert);
	return $result;
}
function createUserProfile($id)
{
	$insert  = 'INSERT INTO '.DB_PERFIX.'user_profile (`id` , `views`)'; 
	$insert .= 'VALUES ('.$id.' , 0);';
	
	$result = mysql_query($insert);
	return $result;
}

function getUsersList($type, $limit=20)
{
	switch ($type)
	{
		case 'recent':
			$whereString = '';
			$orderString = 'ORDER BY registerDate DESC';
			break;  
		case 'random':
			$whereString = '';
			$orderString = 'ORDER BY NULL';
			break;  
		default:
			$whereString = '';
			$orderString = 'ORDER BY u.id';
	}
	$selectString = 'id, username, image';
	
	$select = ' SELECT '.$selectString.' FROM '.DB_PERFIX.'users '.
			  $whereString.$orderString.' LIMIT '.$limit.';';
			  
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$users[$i]['id'] = $row['id'];
			$users[$i]['username'] = $row['username'];
			$users[$i]['image'] = $row['image'];
			$i++;
		}
		return $users;
	}
}

function searchUsersAll($username='', $country='', $state=0, $gender=0, $age=0, $order=0, $limit=20)
{
	$whereString = 'WHERE u.id > 0 ';
	if($username != '')
	{
		$username 	  = strip_tags(trim($username));
		$whereString .= ' AND u.username LIKE ("'.$username.'%") ';
	}
	if($country != '')
	{
		$country 	  = strip_tags(trim($country));
		$whereString .= ' AND ud.country LIKE ("'.$country.'") ';
	}
	if($state > 0)
	{
		$whereString .= ' AND ud.state='.$state.' ';
	}
	if($gender > 0)
	{
		$whereString .= ' AND ud.gender='.$gender.' ';
	}
	if($age > 0)
	{
		$minage = mktime(0,0,0,date("m"),date("d"),date("Y")-$age);
		$minage = date("Y-m-d",$minage);
	
		$maxage = mktime(0,0,0,date("m"),date("d"),(date("Y")-($age+4)));
		$maxage = date("Y-m-d",$maxage);
		
		$whereString .= ' AND ud.bdate < "'.$minage.'" ';
		$whereString .= ' AND ud.bdate > "'.$maxage.'" ';
	}
	switch ($order)
	{
		case 0:
			$orderString = 'ORDER BY u.username ASC ';
			break;  
		case 1:
			$orderString = 'ORDER BY ud.bdate DESC ';
			break; 
	}
	
	if($limit == 0)
	{ $limit = ''; }
	else
	{
		if($limit == "")
		{ $limit = ' LIMIT 20'; }
		else
		{ $limit = ' LIMIT '.$limit; }
	}
	
	$time = mktime(date("H"), date("i")-USER_TIMEOUT, date("s"), date("m"), date("d"),  date("Y"));
	$time_chek = date("Y-m-d H:i:s",$time);
			
	$selectString = ' DISTINCT u.id, u.username, u.image, u.lastvisitDate, ud.gender, ud.country, ud.city, ud.bdate, ur.stars, ur.votes ';

	$select = ' SELECT '.$selectString.' FROM '.DB_PERFIX.'users AS u ';
	$select = $select.' LEFT JOIN '.DB_PERFIX.'user_rating AS ur ON ur.user_id=u.id ';
	$select = $select.' LEFT JOIN '.DB_PERFIX.'user_details AS ud ON ud.id=u.id '.$whereString.$orderString.$limit.';';
	
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$users[$i]['id'] = $row['id'];
			$users[$i]['username'] = $row['username'];
			$users[$i]['image'] = $row['image'];
			
			$users[$i]['gender'] = $row['gender'];
			if($users[$i]['gender'] == 1)
			{ $users[$i]['gendertxt'] = 'Male'; }
			else
			{ $users[$i]['gendertxt'] = 'Female'; }
			$users[$i]['country'] = $row['country'];
			$users[$i]['city'] = $row['city'];
			
			$users[$i]['bdate'] = $row['bdate'];
			$users[$i]['bday'] = substr($row['bdate'],8,2);
			$users[$i]['bmonth'] = substr($row['bdate'],5,2);
			$users[$i]['byear'] = substr($row['bdate'],0,4);
			$users[$i]['age'] = getUserAge($users[$i]['bday'], $users[$i]['bmonth'], $users[$i]['byear']); 
			//echo $user[$i]['starost'];
			if(date("Y-m-d H:i:s", strtotime($row['lastvisitDate'])) < $time_chek)
			{ $users[$i]['status'] = 'offline'; }
			else
			{ $users[$i]['status'] = 'online'; }
			
			$users[$i]['stars'] = $row['stars'];
			$users[$i]['votes'] = $row['votes'];
			if(($users[$i]['stars'] > 0) && ($users[$i]['votes'] > 0))
			{ $users[$i]['avg'] = round(($users[$i]['stars']/$users[$i]['votes']),2); }
			else
			{ $users[$i]['avg'] = 0; }
			$i++;
		}
		return $users;
	}
}

function getUsersAll($type, $limit=20)
{
	if($limit == 0)
	{ $limit = ''; }
	else
	{
		if($limit == "")
		{ $limit = ' LIMIT 20'; }
		else
		{ $limit = ' LIMIT '.$limit; }
	}
	switch ($type)
	{
		case 'recent':
			$whereString = '';
			$orderString = 'ORDER BY u.registerDate DESC ';
			break;  
		case 'random':
			$whereString = '';
			$orderString = 'ORDER BY NULL ';
			break; 
		case 'featured':
			$whereString = '';
			$orderString = 'ORDER BY ur.stars DESC ';
			break; 
		default:
			$whereString = '';
			$orderString = 'ORDER BY u.id ';
	}
	$time = mktime(date("H"), date("i")-USER_TIMEOUT, date("s"), date("m"), date("d"),  date("Y"));
	$time_chek = date("Y-m-d H:i:s",$time);
			
	$selectString = ' DISTINCT u.id, u.username, u.image, u.lastvisitDate, ud.gender, ud.country, ud.city, ud.bdate, ur.stars, ur.votes ';

	$select = ' SELECT '.$selectString.' FROM '.DB_PERFIX.'users AS u ';
	$select = $select.' LEFT JOIN '.DB_PERFIX.'user_rating AS ur ON ur.user_id=u.id ';
	$select = $select.' LEFT JOIN '.DB_PERFIX.'user_details AS ud ON ud.id=u.id '.$whereString.$orderString.$limit.';';
	
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$users[$i]['id'] = $row['id'];
			$users[$i]['username'] = $row['username'];
			$users[$i]['image'] = $row['image'];
			
			$users[$i]['gender'] = $row['gender'];
			if($users[$i]['gender'] == 1)
			{ $users[$i]['gendertxt'] = 'Male'; }
			else
			{ $users[$i]['gendertxt'] = 'Female'; }
			$users[$i]['country'] = $row['country'];
			$users[$i]['city'] = $row['city'];
			
			$users[$i]['bdate'] = $row['bdate'];
			$users[$i]['bday'] = substr($row['bdate'],8,2);
			$users[$i]['bmonth'] = substr($row['bdate'],5,2);
			$users[$i]['byear'] = substr($row['bdate'],0,4);
			$users[$i]['age'] = getUserAge($users[$i]['bday'], $users[$i]['bmonth'], $users[$i]['byear']); 
			//echo $user[$i]['starost'];
			if(date("Y-m-d H:i:s", strtotime($row['lastvisitDate'])) < $time_chek)
			{ $users[$i]['status'] = 'offline'; }
			else
			{ $users[$i]['status'] = 'online'; }
			
			$users[$i]['stars'] = $row['stars'];
			$users[$i]['votes'] = $row['votes'];
			if(($users[$i]['stars'] > 0) && ($users[$i]['votes'] > 0))
			{ $users[$i]['avg'] = round(($users[$i]['stars']/$users[$i]['votes']),2); }
			else
			{ $users[$i]['avg'] = 0; }
			$i++;
		}
		return $users;
	}
}

function getMembersList($type, $limit=20)
{
	if($limit == 0)
	{ $limit = ''; }
	else
	{
		if($limit == "")
		{ $limit = ' LIMIT 20'; }
		else
		{ $limit = ' LIMIT '.$limit; }
	}
	switch ($type)
	{
		case 'recent':
			$whereString = '';
			$orderString = 'ORDER BY u.registerDate DESC ';
			break;  
		case 'random':
			$whereString = '';
			$orderString = 'ORDER BY NULL ';
			break; 
		case 'featured':
			$whereString = '';
			$orderString = 'ORDER BY ur.stars DESC ';
			break; 
		default:
			$whereString = '';
			$orderString = 'ORDER BY u.id ';
	}
	
	$time = mktime(date("H"), date("i")-USER_TIMEOUT, date("s"), date("m"), date("d"),  date("Y"));
	$time_chek = date("Y-m-d H:i:s",$time);
			
	$selectString = ' DISTINCT u.id, u.email, u.username, u.image, u.lastvisitDate, ud.gender, ud.country, ud.state, ud.city, ud.bdate, ud.online_time, ur.stars, ur.votes ';

	$select = ' SELECT '.$selectString.' FROM '.DB_PERFIX.'users AS u ';
	$select = $select.' LEFT JOIN '.DB_PERFIX.'user_rating AS ur ON ur.user_id=u.id ';
	$select = $select.' LEFT JOIN '.DB_PERFIX.'user_details AS ud ON ud.id=u.id ';
	$select = $select.$whereString.$orderString.$limit.';';
	
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$users[$i]['id'] = $row['id'];
			$users[$i]['username'] = $row['username'];
			$users[$i]['email'] = $row['email'];
			$users[$i]['image'] = $row['image'];
			
			$users[$i]['gender'] = $row['gender'];
			if($users[$i]['gender'] == 1)
			{ $users[$i]['gendertxt'] = 'Male'; }
			else
			{ $users[$i]['gendertxt'] = 'Female'; }
			$users[$i]['country'] = $row['country'];
			$users[$i]['state'] = $row['state'];
			if($users[$i]['state'] > 0)
			{ $users[$i]['state_name'] = getStateName($users[$i]['state']); }
			$users[$i]['city'] = $row['city'];
			$users[$i]['bdate'] = $row['bdate'];
			$users[$i]['bday'] = substr($row['bdate'],8,2);
			$users[$i]['bmonth'] = substr($row['bdate'],5,2);
			$users[$i]['byear'] = substr($row['bdate'],0,4);
			$users[$i]['age'] = getUserAge($users[$i]['bday'], $users[$i]['bmonth'], $users[$i]['byear']); 
			$users[$i]['online_time'] = $row['online_time'];
			
			//echo $user[$i]['starost'];
			if(date("Y-m-d H:i:s", strtotime($row['lastvisitDate'])) < $time_chek)
			{ $users[$i]['status'] = 'offline'; }
			else
			{ $users[$i]['status'] = 'online'; }
			
			$users[$i]['stars'] = $row['stars'];
			$users[$i]['votes'] = $row['votes'];
			if(($users[$i]['stars'] > 0) && ($users[$i]['votes'] > 0))
			{ $users[$i]['avg'] = round(($users[$i]['stars']/$users[$i]['votes']),2); }
			else
			{ $users[$i]['avg'] = 0; }
			$i++;
		}
		return $users;
	}
}

function postUserVote($voterid, $userid, $stars)
{
	$select = 'SELECT user_id FROM '.DB_PERFIX.'user_rating WHERE user_id='.$userid.' LIMIT 1;';
	$result = mysql_query($select);
	if(!($result[0]['user_id'] > 0))
	{
		createUserRating($userid);
	}
	
	$select = 'SELECT user_id, voter_id FROM '.DB_PERFIX.'user_votes WHERE user_id="'.$userid.'" AND voter_id='.$voterid.' LIMIT 1;';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$update = 'UPDATE '.DB_PERFIX.'user_votes SET stars='.$stars.' WHERE user_id="'.$userid.'" AND voter_id='.$voterid.' ;';
		$result = mysql_query($update);
		return $result;
	}
	else
	{
		$insert  = 'INSERT INTO '.DB_PERFIX.'user_votes (`user_id` , `voter_id` , `stars`)'; 
		$insert .= 'VALUES ('.$userid.' , '.$voterid.' , '.$stars.');';
		$result = mysql_query($insert);
		return $result;
	}
}

function calculateRating()
{
	$select = 'SELECT user_id FROM '.DB_PERFIX.'user_rating;';
	$result = mysql_query($select);
	$i=0;
	while($row = mysql_fetch_array($result))
	{
		$items[$i]['id'] = $row['user_id'];
		$i++;
	}
	foreach($items as $item)
	{
		$select = 'SELECT COUNT(id) , SUM(stars) FROM '.DB_PERFIX.'user_votes WHERE user_id='.$item['id'].';';
		$result = mysql_query($select);
		$j=0;
		while($row = mysql_fetch_array($result))
		{
			$votes[$j] = $row['COUNT(id)'];
			$stars[$j] = $row['SUM(stars)'];
			$update = 'UPDATE '.DB_PERFIX.'user_rating SET stars='.$stars[$j].', votes='.$votes[$j].' WHERE user_id="'.$item['id'].'" LIMIT 1;';
			$updated = mysql_query($update);
		}
	}
}
function getStateName($id)
{	
	$select = 'SELECT name FROM '.DB_PERFIX.'states WHERE id='.$id.';';
	$result = mysql_query($select);
	while($row = mysql_fetch_array($result))
	{
		$item = $row['name'];
	}
	return $item;
}
function setUserPmStatus($userid, $messageid, $status)
{	
	$update = 'UPDATE '.DB_PERFIX.'user_pm SET status='.$status.' WHERE to_id='.$userid.' AND id='.$messageid.';';
	$result = mysql_query($update);
	return $result;
}
function getUserPmCount($userid)
{	
	$select = 'SELECT COUNT(*) as pm FROM '.DB_PERFIX.'user_pm WHERE to_id='.$userid.';';
	$result = mysql_query($select);
	while($row = mysql_fetch_array($result))
	{
		$user['pm'] = $row['pm'];
	}
	return $user['pm'];
}
function getUserNewPmCount($userid)
{	
	$select = 'SELECT COUNT(*) as newpm FROM '.DB_PERFIX.'user_pm WHERE to_id='.$userid.' AND `status`=0;';
	$result = mysql_query($select);
	while($row = mysql_fetch_array($result))
	{
		$user['newpm'] = $row['newpm'];
	}
	return $user['newpm'] ;
}
function getUserPm($userid)
{
	$limit = ' LIMIT 30';
	$order = ' pm.date_sent DESC ';
	$select = 'SELECT pm.id, pm.subject, pm.message, pm.status, pm.date_sent, u.id AS userid, u.username, u.image FROM '.DB_PERFIX.'user_pm AS pm, '.DB_PERFIX.'users AS u WHERE pm.to_id='.$userid.' AND pm.from_id=u.id ORDER BY '.$order.' '.$limit.';';
	$result = mysql_query($select);

	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$item[$i]['id'] = $row['id'];
			$item[$i]['userid'] = $row['userid'];
			$item[$i]['username'] = $row['username'];
			$item[$i]['image'] = $row['image'];
			$item[$i]['subject'] = $row['subject'];
			$item[$i]['message'] = $row['message'];
			$item[$i]['status'] = $row['status'];
			$item[$i]['date_sent'] = $row['date_sent'];
			$i++;
		}
		return $item;
	}
}
function getUserPmSent($userid)
{
	$limit = ' LIMIT 30';
	$order = ' pm.date_sent DESC ';
	$select = 'SELECT pm.id, pm.subject, pm.message, pm.status, pm.date_sent, u.id AS userid, u.username, u.image FROM '.DB_PERFIX.'user_pm AS pm, '.DB_PERFIX.'users AS u WHERE pm.from_id='.$userid.' AND pm.to_id=u.id ORDER BY '.$order.' '.$limit.';';
	$result = mysql_query($select);

	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$item[$i]['id'] = $row['id'];
			$item[$i]['userid'] = $row['userid'];
			$item[$i]['username'] = $row['username'];
			$item[$i]['image'] = $row['image'];
			$item[$i]['subject'] = $row['subject'];
			$item[$i]['message'] = $row['message'];
			$item[$i]['status'] = $row['status'];
			$item[$i]['date_sent'] = $row['date_sent'];
			$i++;
		}
		return $item;
	}
}
function sendUserPm($from_id, $to_id, $subject, $message)
{
	$subject = strip_tags(trim($subject));
	$message = stripslashes($message);
	$insert = 'INSERT INTO '.DB_PERFIX.'user_pm (`id`, `from_id`, `to_id`, `subject`, `message`, `status`, `date_sent`)';
	$insert .= 'VALUES (NULL, '.$from_id.', '.$to_id.', \''.$subject.'\', \''.$message.'\', 0, NOW());';
	$result = mysql_query($insert);
	return $result;
}
function delUserPm($pmid, $userid)
{
	$delete = 'DELETE FROM '.DB_PERFIX.'user_pm WHERE id='.$pmid.' AND to_id='.$userid.';';
	$result = mysql_query($delete);
}
function getUserCommentCount($userid)
{	
	$select = 'SELECT COUNT(*) as comments FROM '.DB_PERFIX.'user_comments WHERE to_id='.$userid.';';
	$result = mysql_query($select);
	while($row = mysql_fetch_array($result))
	{
		$count = $row['comments'];
	}
	return $count;
}

function getUserNewCommentCount($userid)
{	
	$select = ' SELECT  COUNT(*) as newcount FROM '.DB_PERFIX.'user_comments WHERE to_id='.$userid.' AND `read`=0;';
	$result = mysql_query($select);
	while($row = mysql_fetch_array($result))
	{
		$newcount = $row['newcount'];
	}
	return $newcount;
}

function getUserComments($userid, $limit="")
{
	if($limit == "")
	{
		$limit = ' LIMIT 10, 10';
	}
	else
	{
		$limit = ' LIMIT '.$limit.', 40';
	}
	
	$select = 'SELECT uc.id, uc.comment, uc.read, uc.embed, uc.to_id, uc.from_id, u.username, u.image FROM '.DB_PERFIX.'user_comments AS uc, '.DB_PERFIX.'users AS u WHERE uc.to_id='.$userid.' AND uc.from_id=u.id '.$limit.';';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$item[$i]['id'] = $row['id'];
			$item[$i]['to_id'] = $row['to_id'];
			$item[$i]['from_id'] = $row['from_id'];
			$item[$i]['username'] = $row['username'];
			$item[$i]['image'] = $row['image'];
			$item[$i]['comment'] = $row['comment'];
			$item[$i]['embed'] = $row['embed'];
			$i++;
		}
		return $item;
	}
}
function postUserComment($from_id, $to_id, $comment)
{
	
	$comment = stripslashes(strip_tags(trim($comment)));
	if(($from_id > 0) && ($to_id > 0) && ($comment != ''))
	{
		
		$insert = 'INSERT INTO '.DB_PERFIX.'user_comments (`id`, `from_id`, `to_id`, `comment`, `date`)';
		$insert .= 'VALUES (NULL, '.$from_id.', '.$to_id.', "'.$comment.'", NOW());';
		$result = mysql_query($insert);
		return $result;
	}
	
}
function delUserComment($comid, $userid)
{
	$delete = 'DELETE FROM '.DB_PERFIX.'user_comments WHERE id='.$comid.' AND (from_id='.$userid.' OR to_id='.$userid.');';
	$result = mysql_query($delete);
}
function saveAboutUser($id, $about='NULL')
{
	$about = strip_tags(trim($about));
	if(getUserAllProfile($id))
	{	
		$update = 'UPDATE '.DB_PERFIX.'user_profile SET about="'.$about.'" WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{ return $about; }
	}
}
function saveSportsUser($id, $sports='NULL')
{
	$sports = strip_tags(trim($sports));
	if(getUserAllProfile($id))
	{	
		$update = 'UPDATE '.DB_PERFIX.'user_profile SET sports="'.$sports.'" WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{ return $sports; }
	}
}
function saveStatsUser($id, $stats='NULL')
{
	$stats = strip_tags(trim($stats));
	if(getUserAllProfile($id))
	{	
		$update = 'UPDATE '.DB_PERFIX.'user_profile SET stats="'.$stats.'" WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{ return $stats; }
	}
}
function saveTeamsUser($id, $teams='NULL')
{
	$teams = strip_tags(trim($teams));
	if(getUserAllProfile($id))
	{	
		$update = 'UPDATE '.DB_PERFIX.'user_profile SET teams="'.$teams.'" WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{ return $teams; }
	}
}
function saveTeamsDissUser($id, $teamsdiss='NULL')
{
	$teamsdiss = strip_tags(trim($teamsdiss));
	if(getUserAllProfile($id))
	{	
		$update = 'UPDATE '.DB_PERFIX.'user_profile SET teams_diss="'.$teamsdiss.'" WHERE id='.$id.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{ return $teamsdiss; }
	}
}
function getUserTeams($userid)
{
	$select = 'SELECT id, name, link, image, embed, diss FROM '.DB_PERFIX.'user_teams_sd WHERE user_id='.$userid.';';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$team[$i]['id'] = $row['id'];
			$team[$i]['name'] = $row['name'];
			$team[$i]['link'] = $row['link'];
			$team[$i]['image'] = $row['image'];
			$team[$i]['embed'] = $row['embed'];
			$team[$i]['diss'] = $row['diss'];
			$i++;
		}
		return $team;
	}
}
function setUserBg($userid, $bgid)
{
	$select = 'SELECT name, path FROM '.DB_PERFIX.'backgrounds WHERE id='.$bgid.';';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$bgpath = $row['path'];
		}
	}
	$select = 'SELECT bg FROM '.DB_PERFIX.'user_profile WHERE id='.$userid.';';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$old_image = $row['bg'];
		}
	}
	
	if($bgpath != '')
	{	
		$extension = substr($bgpath,-3);
		$new_name = $userid.md5(uniqid()).".".$extension;

		$update = 'UPDATE '.DB_PERFIX.'user_profile SET bg="'.$new_name.'" WHERE id='.$userid.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{
			if (is_file(PROFILE_BG_PATH.$old_image))
			{
				if (!unlink(PROFILE_BG_PATH.$old_image))
				{$error['bg_image'] = "Error deleting old bg image ";}
				else
				{$error['bg_image'] = 'Deleted old image';}
				
				if (!unlink(PROFILE_BG_THUMB_PATH.$old_image))
				{$error['bg_image'] = "Error deleting old profile image ";}
			}
			copy(BGS_PATH.$bgpath, PROFILE_BG_PATH.$new_name);
			copy(BGS_THUMB_PATH.$bgpath, PROFILE_BG_THUMB_PATH.$new_name);
		}
		return $result;
	}
}
function setUserBgStyle($userid, $style)
{
	$update = 'UPDATE '.DB_PERFIX.'user_profile SET bg_style="'.$style.'" WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($update);
	return $result;
}
function addUserFriend($userid, $friend_id)
{
	$select = 	'SELECT user_id, friend_id '.
				'FROM '.DB_PERFIX.'user_friends '. 
			    'WHERE (user_id='.$userid.' AND friend_id='.$friend_id.') OR (friend_id='.$userid.' AND user_id='.$friend_id.');';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		return;
	}
	else
	{
		$insert = 'INSERT INTO '.DB_PERFIX.'user_friends (`id`, `user_id`, `friend_id`, `status`)';
		$insert .= 'VALUES (NULL, '.$userid.', '.$friend_id.', 0);';
		$result = mysql_query($insert);
		return $result;
	}	
}
function getUsersFriends($userid, $limit=20)
{
	$select = 	'SELECT DISTINCT u.id, u.username, u.image '.
				'FROM '.DB_PERFIX.'users AS u, '.DB_PERFIX.'user_friends AS uf '. 
			    'WHERE u.id<>'.$userid.' AND ((uf.user_id='.$userid.') OR (uf.friend_id='.$userid.')) AND ((uf.friend_id=u.id) OR (uf.user_id=u.id)) AND uf.status=1 LIMIT '.$limit.';';
	  
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$friends[$i]['id'] = $row['id'];
			$friends[$i]['username'] = $row['username'];
			$friends[$i]['image'] = $row['image'];
			$friends[$i]['status'] = 1;
			$i++;
		}
		return $friends;
	}
}

function getUsersFriendsReqCnt($userid)
{
	$select = 	'SELECT COUNT(id) as requests '.
				'FROM '.DB_PERFIX.'user_friends '. 
			    'WHERE friend_id='.$userid.' AND status=0;';
	$result = mysql_query($select);
	$requests = 0;
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$requests = $row['requests'];
		}
	}
	return $requests;
}
function getUsersFriendsReq($userid, $limit=20)
{
	$select = 	'SELECT DISTINCT u.id, u.username, u.image '.
				'FROM '.DB_PERFIX.'users AS u, '.DB_PERFIX.'user_friends AS uf '. 
			    'WHERE u.id<>'.$userid.' AND (uf.friend_id='.$userid.') AND (uf.user_id=u.id) AND uf.status=0 LIMIT '.$limit.';';
	  
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$friends[$i]['id'] = $row['id'];
			$friends[$i]['username'] = $row['username'];
			$friends[$i]['image'] = $row['image'];
			$friends[$i]['status'] = 0;
			$i++;
		}
		return $friends;
	}
}
function getUsersFriendsPend($userid, $limit=20)
{
	$select = 	'SELECT DISTINCT u.id, u.username, u.image '.
				'FROM '.DB_PERFIX.'users AS u, '.DB_PERFIX.'user_friends AS uf '. 
			    'WHERE u.id<>'.$userid.' AND (uf.user_id='.$userid.') AND (uf.friend_id=u.id) AND uf.status=0 LIMIT '.$limit.';';
	  
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		$i = 0;
		while($row = mysql_fetch_array($result))
		{
			$friends[$i]['id'] = $row['id'];
			$friends[$i]['username'] = $row['username'];
			$friends[$i]['image'] = $row['image'];
			$friends[$i]['status'] = 2;
			$i++;
		}
		return $friends;
	}
}

function deleteFriend($friendid, $userid)
{
	$delete = 'DELETE FROM '.DB_PERFIX.'user_friends WHERE friend_id='.$userid.' AND user_id='.$friendid.' AND status=1 LIMIT 1;';
	$result = mysql_query($delete);
	$delete = 'DELETE FROM '.DB_PERFIX.'user_friends WHERE status=1 AND user_id='.$userid.' AND friend_id='.$friendid.' AND status=1 LIMIT 1;';
	$result = mysql_query($delete);
	return $result;
}
function approveFriend($userid, $friendid)
{
	$update = 'UPDATE '.DB_PERFIX.'user_friends SET status=1 WHERE status=0 AND friend_id='.$userid.' AND user_id='.$friendid.' LIMIT 1;';
	$result = mysql_query($update);
	return $result;
}
function denyFriend($userid, $friendid)
{
	$update = 'DELETE FROM '.DB_PERFIX.'user_friends WHERE status=0 AND friend_id='.$userid.' AND user_id='.$friendid.' LIMIT 1;';
	$result = mysql_query($update);
	return $result;
}
function delRequest($userid, $friendid)
{
	$update = 'DELETE FROM '.DB_PERFIX.'user_friends WHERE status=0 AND friend_id='.$friendid.' AND user_id='.$userid.' LIMIT 1;';
	$result = mysql_query($update);
	return $result;
}
function addProfileView($userid, $viewer_id)
{
	$update = 'UPDATE '.DB_PERFIX.'user_profile SET views=views+1 WHERE id='.$userid.' LIMIT 1;';
	$result = mysql_query($update);
	return $result;
}


/* SPORTSDISS FUNCTIONS */
function getUserLogo($userid)
{
	$item = '';
	if($userid > 0)
	{
		$select = 'SELECT logo FROM '.DB_PERFIX.'user_profile WHERE id='.$userid.' LIMIT 1;';
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{
				$item['logo'] = $row['logo'];
			}
		}
	}
	return $item;
}
function setUserLogo($userid, $bgid)
{
	$select = 'SELECT name, path FROM '.DB_PERFIX.'logo WHERE id='.$bgid.';';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$bgpath = $row['path'];
		}
	}
	$select = 'SELECT logo FROM '.DB_PERFIX.'user_profile WHERE id='.$userid.';';
	$result = mysql_query($select);
	if(mysql_num_rows($result) > 0)
	{
		while($row = mysql_fetch_array($result))
		{
			$old_image = $row['logo'];
		}
	}
	
	if($bgpath != '')
	{	
		$extension = substr($bgpath,-3);
		$new_name = $userid.md5(uniqid()).".".$extension;

		$update = 'UPDATE '.DB_PERFIX.'user_profile SET logo="'.$new_name.'" WHERE id='.$userid.' LIMIT 1;';
		$result = mysql_query($update);
		if($result > 0)
		{
			if (is_file(USER_IMAGE_PATH.$old_image))
			{
				if (!unlink(USER_IMAGE_PATH.$old_image))
				{$error['bg_image'] = "Error deleting old bg image ";}
				else
				{$error['bg_image'] = 'Deleted old image';}
				
				if (!unlink(USER_IMAGE_PATH.'thumbs/'.$old_image))
				{$error['bg_image'] = "Error deleting old profile image ";}
			}
			copy(LOGOS_PATH.$bgpath, USER_IMAGE_PATH.$new_name);
			copy(LOGOS_THUMB_PATH.$bgpath, USER_IMAGE_PATH.'thumbs/'.$new_name);
		}
		return $result;
	}
}
?>
